<?php

namespace app\common\model;

use think\Model;

class MenuModel extends Model
{
    //
    protected $table = 'sys_menu';

    /**
     * @return array|mixed|null|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function login_menu()
    {
        $login_user_menus = session('loginUserMenus');
        if ($login_user_menus != null) {
            return $login_user_menus;
        }
        //获取登录用户相应菜单
        $user_id = session('loginUserId');
        $users = (new UserModel)->where('id', $user_id)->select();
        if (count($users) != 1) {
            return null;
        }

        $role_id = $users[0]->role_id;
        $permissions = (new PermissionModel)->where('role_id', $role_id)->select();
        $menu_ids = array();
        for ($i = 0; $i < count($permissions); $i++) {
            $menu_ids[$i] = $permissions[$i]->menu_id;
        }

        $loginUserMenu = (new MenuModel)->where('is_menu', '=', '1')
            ->where('id', 'in', $menu_ids)
            ->order('sort', 'asc')->select();

        foreach ($loginUserMenu as $key => $val) {
            $url = '';
            if ($val->module_name) {
                $url .= '/' . $val->module_name;
            }

            if($val->action_name){
                $url .= '/' . $val->action_name;
            }

            if ($val->function_name) {
                $url .= '/' . $val->function_name;
            }

            $loginUserMenu[$key]['url'] = $url;
        }
        session("loginUserMenus", $loginUserMenu);
        return $loginUserMenu;
    }
}
